package com.fansea.ai.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fansea.ai.domain.Agent;
import com.fansea.ai.domain.AgentKnowledge;
import com.fansea.ai.domain.Knowledge;
import com.fansea.ai.domain.dto.AjaxResult;
import com.fansea.ai.service.AgentKnowledgeService;
import com.fansea.ai.service.AgentService;
import com.fansea.ai.service.KnowledgeService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Projectname: Spring-AI
 * @Filename: AgentController
 * @Author: FANSEA
 * @Date:2025/5/3 20:03
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/agent")
public class AgentController {

    private final AgentService agentService;
    private final AgentKnowledgeService agentKnowledgeService;
    private final KnowledgeService knowledgeService;

    @GetMapping("/agentToKnowledge")
    public AjaxResult agentToKnowledge(Long agentId,Long knowledgeId) {
        agentKnowledgeService.save(new AgentKnowledge(agentId,knowledgeId));
        return AjaxResult.success();
    }
    
    @GetMapping("/knowledge/list")
    public AjaxResult knowledgeList(Long agentId) {
        List<AgentKnowledge> list = agentKnowledgeService.list(new LambdaQueryWrapper<AgentKnowledge>().eq(AgentKnowledge::getAgentId, agentId));
        List<Knowledge> knowledges = list.stream().map(ak -> knowledgeService.getById(ak.getKnowledgeId())).toList();
        return AjaxResult.success(knowledges);
    }

    
    
    // 新增 Agent
    @PostMapping("/add")
    public AjaxResult addAgent(@RequestBody Agent agent) {
        agentService.save(agent);
        return AjaxResult.success();
    }

    // 更新 Agent
    @PutMapping("/update/{id}")
    public AjaxResult updateAgent(@PathVariable Long id, @RequestBody Agent agent) {
        agent.setId(id);
        agentService.updateById(agent);
        return AjaxResult.success();
    }

    // 删除 Agent
    @DeleteMapping("/delete/{id}")
    public AjaxResult deleteAgent(@PathVariable Long id) {
        agentService.removeById(id);
        return AjaxResult.success();
    }

    // 删除 Agent
    @DeleteMapping("/delete/knowledge/{knowledgeId}")
    public AjaxResult deleteAgentAndKnowledge(Long agentId, @PathVariable Long knowledgeId) {
        agentKnowledgeService.remove(new LambdaQueryWrapper<AgentKnowledge>()
                .eq(AgentKnowledge::getAgentId, agentId)
                .eq(AgentKnowledge::getKnowledgeId, knowledgeId));
        return AjaxResult.success();
    }

    // 查询特定 Agent
    @GetMapping("/{id}")
    public AjaxResult getAgentById(@PathVariable Long id) {
        return AjaxResult.success(agentService.getById(id));
    }

    // 查询所有 Agent
    @GetMapping("/list")
    public AjaxResult getAllAgents() {
        return AjaxResult.success(agentService.list());
    }

}
